package uf.audit.util;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.jfinal.plugin.activerecord.Record;

import uf.audit.util.poi.POIExporter;
import uf.audit.util.poi.POIExtractor;
import uf.audit.util.poi.SheetConfig;

public class ExportConfigUtil {

	private static final LinkedHashMap<String, List<SheetConfig>> moduleConfigMap = new LinkedHashMap<String, List<SheetConfig>>();

	private static LinkedHashMap<String, List<SheetConfig>> initModuleConfig() {
		if (moduleConfigMap.isEmpty()) {
			try {
				Document xmlDocument = XmlUtil.loadXmlDocument(
						Thread.currentThread().getContextClassLoader().getResourceAsStream("/moduleConfig.xml"));
				NodeList moduleNodeList = XmlUtil.selectNodes("/config/module", xmlDocument);
				for (int moduleIndex = 0, moduleNumber = moduleNodeList
						.getLength(); moduleIndex < moduleNumber; moduleIndex++) {
					Node moduleNode = moduleNodeList.item(moduleIndex);
					if (Node.ELEMENT_NODE == moduleNode.getNodeType()) {
						Element element = (Element) moduleNode;
						String moduleSymbol = element.getAttribute("moduleSymbol");
						if (moduleSymbol == null || moduleSymbol.length() == 0) {
							continue;
						}
						NodeList sheetNodeList = XmlUtil.selectNodes(
								String.format("/config/module[@moduleSymbol='%s']/sheet", moduleSymbol), xmlDocument);
						if (sheetNodeList != null && sheetNodeList.getLength() > 0) {
							List<SheetConfig> sheetConfigList = new ArrayList<SheetConfig>();
							for (int sheetIndex = 0, sheetNumber = sheetNodeList
									.getLength(); sheetIndex < sheetNumber; sheetIndex++) {
								Node sheetNode = sheetNodeList.item(sheetIndex);
								if (Node.ELEMENT_NODE == sheetNode.getNodeType()) {
									SheetConfig sheetConfig = new SheetConfig();
									NodeList columnNodeList = XmlUtil.selectNodes("./column", sheetNode);
									for (int columnIndex = 0, columnNumber = columnNodeList
											.getLength(); columnIndex < columnNumber; columnIndex++) {
										Node columnNode = columnNodeList.item(columnIndex);
										if (Node.ELEMENT_NODE == columnNode.getNodeType()) {
											Element columnElement = (Element) columnNode;
											String columnName = columnElement.getAttribute("columnName");
											String displayName = columnElement.getAttribute("displayName");
											String columnWidth = columnElement.getAttribute("columnWidth");
											String importFlag = columnElement.getAttribute("import");

											sheetConfig.addHeader(displayName);
											sheetConfig.addColumn(columnName);
											sheetConfig.addColumnWidth(StringUtils.isNumeric(columnWidth)
													? Integer.parseInt(columnWidth) * 256 : 200 * 256);
											if ("true".equals(importFlag)) {
												sheetConfig.addImportColumnMap(displayName, columnName);
											}
										}
									}
									sheetConfigList.add(sheetConfig);
								}
							}
							moduleConfigMap.put(moduleSymbol, sheetConfigList);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return moduleConfigMap;
	}

	public static List<SheetConfig> getModuleConfig(String moduleSymbol) {
		initModuleConfig();
		if (moduleConfigMap.containsKey(moduleSymbol)) {
			return moduleConfigMap.get(moduleSymbol);
		} else {
			return null;
		}
	}

	public static String initDownloadRootPath() {
		String downloadRootPath = Utils.getAttachmentDir("");
		File file = new File(downloadRootPath);
		if (!file.exists()) {
			file.mkdirs();
		}
		return downloadRootPath;
	}

	public static synchronized String creatExcelFileName(String fileName, String fileExt) {
		return fileName + System.currentTimeMillis() + fileExt;
	}

	/**
	 * 生成excel文件
	 * 
	 * @param fileName
	 *            文件名称
	 * @param sheetNameList
	 *            多sheet页名称
	 * @param moduleSymbol
	 *            标识关键字（用于获取导出配置信息）
	 * @param sheetDataList
	 *            多sheet页导出数据集合
	 * @return
	 */
	public static String creatExcelUtil(String fileName, List<String> sheetNameList, String moduleSymbol,
			List<List<Record>> sheetDataList) {
		List<SheetConfig> sheetConfigList = ExportConfigUtil.getModuleConfig(moduleSymbol);
		if (sheetConfigList != null && !sheetConfigList.isEmpty()) {
			String fileNameExt = creatExcelFileName(fileName, ".xls");
			String fileNamePath = ExportConfigUtil.initDownloadRootPath() + File.separator + fileNameExt;
			POIExporter.exportExcel(sheetNameList, sheetConfigList, sheetDataList, fileNamePath);
			return fileNameExt;
		} else {
			return null;
		}
	}

	/**
	 * 生成excel文件
	 * 
	 * @param fileName
	 *            文件名称
	 * @param sheetNameList
	 *            多sheet页名称
	 * @param moduleSymbol
	 *            标识关键字（用于获取导出配置信息）
	 * @param sheetDataList
	 *            多sheet页导出数据集合
	 * @return
	 */
	public static String creatExcelUtil(String fileName, String[] sheetNameArray, String moduleSymbol,
			List<List<Record>> sheetDataList) {
		List<SheetConfig> sheetConfigList = ExportConfigUtil.getModuleConfig(moduleSymbol);
		if (sheetConfigList != null && !sheetConfigList.isEmpty()) {
			String fileNameExt = creatExcelFileName(fileName, ".xls");
			String fileNamePath = ExportConfigUtil.initDownloadRootPath() + File.separator + fileNameExt;
			POIExporter.exportExcel(Arrays.asList(sheetNameArray), sheetConfigList, sheetDataList, fileNamePath);
			return fileNamePath.replace("/", File.separator);
		} else {
			return null;
		}
	}

	/**
	 * 生成excel文件
	 * 
	 * @param fileName
	 *            文件名称
	 * @param sheetName
	 *            sheet页名称
	 * @param moduleSymbol
	 *            标识关键字（用于获取导出配置信息）
	 * @param dataset
	 *            导出数据集合
	 * @return
	 */
	public static String creatExcelUtil(String fileName, String sheetName, String moduleSymbol,
			List<Record> sheetData) {
		List<SheetConfig> sheetConfigList = ExportConfigUtil.getModuleConfig(moduleSymbol);
		if (sheetConfigList != null && !sheetConfigList.isEmpty()) {
			String fileNameExt = creatExcelFileName(fileName, ".xls");
			String fileNamePath = ExportConfigUtil.initDownloadRootPath() + File.separator + fileNameExt;
			POIExporter.exportExcel(sheetName, sheetConfigList.get(0), sheetData, fileNamePath);
			return fileNamePath.replace("/", File.separator);
		} else {
			return null;
		}
	}

	public static Message readExcelData(File file, String moduleSymbol) {
		Message message = new Message();
		try {
			if (file != null && file.exists() && file.isFile()) {
				List<SheetConfig> sheetConfigList = ExportConfigUtil.getModuleConfig(moduleSymbol);
				List<List<String>> multiHeaderList = new ArrayList<List<String>>();
				message = POIExtractor.excelExtractor(file, multiHeaderList, sheetConfigList);
			} else {
				message.setMsg("文件丢失");
			}
		} catch (Exception e) {
			e.printStackTrace();
			message.setMsg("读取数据出错");
		}
		return message;
	}

	public static Message readExcelData(String filePath, String moduleSymbol) {
		return readExcelData(new File(filePath), moduleSymbol);
	}
}